<?php

namespace app\modules\backend\controllers;

use app\models\cacheModel\AdminRoleModel as AdminRoleCacheModel;
use app\models\cacheModel\NewsCategoryModel as NewsCategoryCacheModel;
use app\models\cacheModel\SettingModel as SettingCacheModel;
use app\models\tableModel\AdminRoleModel as AdminRoleDBModel;
use app\models\tableModel\NewsCategoryModel as NewsCategoryDbModel;
use app\models\tableModel\SettingModel as SettingDBModel;
use app\service\tool\UtilsService;
use \yii\console\Exception as consoleException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;

/**
 * 缓存管理
 */
class CacheController extends BaseController
{

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs'  => [ // 请求方式
                'class'   => VerbFilter::className(),
                'actions' => [
                    ### 页面

                    ### 接口
                    'admin-menu'    => ['GET', 'POST'],
                    'setting'       => ['GET', 'POST'],
                    'news-category' => ['GET', 'POST'],
                ],
            ]
        ];
    }

    /**
     * 更新[后台角色菜单]缓存
     *  ` 每次获取20个，更新其缓存 `
     * @return mixed
     */
    public function actionAdminMenu()
    {

        // 操作名称
        $doName = '角色菜单';
        // 第几页
        $page = $this->get('page', 1);
        // 每页最数
        $pageSize = 20;

        ### 增加可以一次刷新规定角色编号线下的缓存
        // PS: 因为有其他地方调用会传输某个编号更新某个角色的缓存
        $idList = $this->post('idList');
        // 传输角色编号，角色编号为空
        if (!empty($idList) && count($idList) <= 0) {

            return $this->jsonFail('刷新' . $doName . '：请选择一个角色条目', 400, [
                'hint' => '未传输任何编号',
            ]);
        }

        ### 首先第一页删除全部缓存
        if (!empty($idList) && $page == 1) AdminRoleCacheModel::deleteAll($idList);

        // 条件
        $where = ['AND'];
        if (!empty($idList)) {
            $where[] = [
                'IN', 'id', is_array($idList) ?
                    $idList : explode(',', $idList)
            ];
        }

        $paginate = AdminRoleDBModel::loadModel()->loadWhere($where)->getPaginate($page, $pageSize, 'id, name');
        // 角色列表
        $roleList = $paginate->getList();
        // 角色总数
        $roleCount = $paginate->getTotal();

        foreach ($roleList as $k => $v) {

            ### 1、清除[数据库]中角色菜单信息
            $roleDb = AdminRoleDBModel::loadModel($v);
            if (!$roleDb) {
                return $this->jsonFail('刷新' . $doName . '：' . $doName .
                    '【' . $v['name'] . '】不存在', 404, [
                    'id'          => $v['id'],
                    'error_hint'  => '角色未找到',
                    'errorColumn' => 'id'
                ]);
            }

            ### 2、清除[缓存]中角色菜单信息
            $roleCache = AdminRoleCacheModel::loadModel($v);
            if (!$roleCache) {
                $roleCache = AdminRoleCacheModel::loadModel();
                $roleCache->setAttributes($roleDb->getAttributes());
            }

            // 赋值菜单
            $roleCache->setAttribute('menu', $roleDb->getMenu());
            // 更新下角色菜单
            if (!$roleCache->save()) {
                $error = UtilsService::getModelError($roleCache->errors);
                return $this->jsonFail('刷新' . $doName . '：' . $doName .
                    '【' . $v['name'] . '】缓存更新失败',
                    400, [
                        'id'          => $v['id'],
                        'error_hint'  => $error['msg'],
                        'errorColumn' => $error['column']
                    ]);
            }
        }

        // 进度
        $allPage = ceil($roleCount / $pageSize);
        // 下一页是否还有数据 - 默认否
        $nextPageHave = false;
        if ($allPage <= $page) {

            $progress = '全部更新完毕';
        } else {

            $progress     = '共' . $allPage . '页/第' . $page . '页';
            $nextPageHave = true;
        }

        return $this->jsonSuccess('刷新' . $doName . '：' . $progress, [
            'nextPageHave' => $nextPageHave
        ]);
    }

    /**
     * 更新[设置]缓存
     *  ` 每次获取20个，更新其缓存 `
     * @throws \yii\db\Exception
     */
    public function actionSetting()
    {

        // 操作名称
        $doName = '设置';
        // 第几页
        $page = $this->get('page', 1);
        // 每页最数
        $pageSize = 20;

        // 条件
        $where = ['AND'];

        ### 首先第一页删除全部缓存
        if ($page == 1) SettingCacheModel::deleteAll();

        $dbModel = SettingDBModel::find();
        // 列表
        $dbList = $dbModel->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->all();
        // 总数
        $dbCount = $dbModel->count();
        foreach ($dbList as $k => $v) {

            ### 1、查询到缓存设置条目
            $cacheData = SettingCacheModel::loadModel($v->getAttribute('key'));
            if (!$cacheData) $cacheData = SettingCacheModel::loadModel();

            // 数据复制
            $cacheData->setAttributes($v->getAttributes());

            ### 2、更新缓存信息
            if (!$cacheData->save(false, null, false)) {

                $error = UtilsService::getModelError($cacheData->errors);
                return $this->jsonFail('刷新' . $doName . '：【' . $v['title'] . '】缓存更新失败',
                    400, [
                        'key'         => $v['key'],
                        'error_hint'  => $error['msg'],
                        'errorColumn' => $error['column']
                    ]);
            }
        }

        // 进度
        $allPage = ceil($dbCount / $pageSize);
        // 下一页是否还有数据 - 默认否
        $nextPageHave = false;
        if ($allPage <= $page) {

            $progress = '全部更新完毕';
        } else {

            $progress     = '共' . $allPage . '页/第' . $page . '页';
            $nextPageHave = true;
        }

        return $this->jsonSuccess('刷新' . $doName . '：' . $progress, [
            'nextPageHave' => $nextPageHave
        ]);
    }

    /**
     * 更新[文章分类]缓存
     *  ` 每次获取20个，更新其缓存 `
     * @throws \yii\db\Exception
     */
    public function actionNewsCategory()
    {

        // 操作名称
        $doName = '文章分类';
        // 第几页
        $page = $this->get('page', 1);
        // 每页最数
        $pageSize = 20;

        // 条件
        $where = ['AND'];

        ### 首先第一页删除全部缓存
        if ($page == 1) NewsCategoryCacheModel::deleteAll();

        $dbModel = NewsCategoryDbModel::find();
        // 列表
        $dbList = $dbModel->orderBy('sort desc, id asc')
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->all();

        // 总数
        $dbCount = $dbModel->count();
        foreach ($dbList as $k => $v) {

            ### 1、查询到缓存条目
            $cacheData = NewsCategoryCacheModel::loadModel($v->getAttribute('id'));
            if (!$cacheData) $cacheData = NewsCategoryCacheModel::loadModel();

            // 数据复制
            $cacheData->setAttributes($v->getAttributes());

            ### 2、刷新缓存
            if (!$cacheData->save(false, null, false)) {

                $error = UtilsService::getModelError($cacheData->errors);
                return $this->jsonFail('刷新' . $doName . '：【' . $v['name'] . '】缓存更新失败',
                    400, [
                        'id'         => $v['id'],
                        'error_hint'  => $error['msg'],
                        'errorColumn' => $error['column']
                    ]);
            }
        }

        // 进度
        $allPage = ceil($dbCount / $pageSize);
        // 下一页是否还有数据 - 默认否
        $nextPageHave = false;
        if ($allPage <= $page) {

            $progress = '全部更新完毕';
        } else {

            $progress     = '共' . $allPage . '页/第' . $page . '页';
            $nextPageHave = true;
        }

        return $this->jsonSuccess('刷新' . $doName . '：' . $progress, [
            'nextPageHave' => $nextPageHave
        ]);
    }
}
